package com.zdp.contentcenter.configuration;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.alibaba.nacos.ribbon.NacosServer;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author sesshomaru
 * @date 2020/9/17
 */
@Slf4j
public class NacosSameClusterWeightRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
    }

    @Override
    public Server choose(Object o) {
        try {

            // 拿到 spring.cloud.nacos.discovery.cluster-name=WH 中当前服务的集群名称，比方说内容中心调用用户中心，
            // 这里获取的就是配置在内容中心配置文件中的集群名称
            String clusterName = nacosDiscoveryProperties.getClusterName();
            log.info("当前服务的集群名称为:{}", clusterName);
            BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
            log.info("lb={}", loadBalancer);

            // 想要请求的微服务的名称
            String name = loadBalancer.getName();

            // 拿到服务发现的相关api
            NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
            // 把目标服务的名字传入 true表示只返回目标服务健康的实例
            // 1. 找到指定服务的所有实例      A
            List<Instance> instances = namingService.selectInstances(name, true);

            // 2. 过滤出相同集群下的所有实例   B
            List<Instance> sameClusterInstance = instances.stream()
                    .filter(instance -> Objects.equals(instance.getClusterName(), clusterName))
                    .collect(Collectors.toList());

            List<Instance> instanceToBeChosen = new ArrayList<>();
            // 3. 如果B是空，就用A
            if (CollectionUtils.isEmpty(sameClusterInstance)) {
                instanceToBeChosen = instances;
                log.warn("发生跨集群调用,name={},clusterName={},instances={}",name,clusterName,instanceToBeChosen);
            } else {
                instanceToBeChosen = sameClusterInstance;
            }
            // 4. 基于权重的负载均衡算法，返回1个实例
            Instance instance = ExtendBalancer.getHostByRandomWeight2(instanceToBeChosen);
            log.info("选择的实例是 port = {}", instance.getPort());
            return new NacosServer(instance);
        } catch (NacosException e) {
            return null;
        }
    }



}

class ExtendBalancer extends Balancer {
    public static Instance getHostByRandomWeight2(List<Instance> hosts) {
        return getHostByRandomWeight(hosts);
    }
}
